import React from 'react'
import ReactDOM from 'react-dom'
import { Spin, Button, Modal, message } from 'antd'
import { WeaInput, WeaColorPicker, WeaDialog, WeaLocaleProvider, WeaTableEditable, WeaTag, WeaRightMenu, WeaInputSearch } from 'ecCom'
import { toJS } from "mobx"
import * as taskMain from '../../apis/task/taskMain'

const getLabel = WeaLocaleProvider.getLabel
const formatMultiLang = WeaLocaleProvider.formatMultiLang

function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
    })
}

export default class TaskTag extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            colorpickerDialogVisible: false,
            spinning: false,
            datas: [],
            searchname: "",
            targetTag: {},    // 被点击的tag
            delTagIds: "",       // 被删除的标签id
            columns: [
                {
                    title: getLabel(81323, '标签名称'),
                    dataIndex: 'name',
                    key: 'name',
                    com: [
                        {
                            type: 'CUSTOM',
                            key: 'name',
                            render: (text, record, index, onEdit) => {
                                return (
                                    <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@3auklk@${record.id}`}
                                        viewAttr={3}
                                        inputType={"multilang"}
                                        // value={formatMultiLang(record.name)}
                                        value={record.name}
                                        onChange={value => {
                                            const { datas } = this.state
                                            datas[index].name = value
                                        }}
                                    />
                                )
                            }
                        }
                    ]
                },
                {
                    title: getLabel(495, '颜色'),
                    dataIndex: 'color',
                    key: 'color',
                    com: [
                        {
                            type: 'CUSTOM',
                            key: 'color',
                            render: (text, record, index, onEdit) => {
                                return (
                                    <span style={{ display: "inline-block" }} onClick={() => { this.onTagClick({ ...record }) }}>
                                        <WeaTag ecId={`${this && this.props && this.props.ecId || ''}_WeaTag@41uohs@${record.id}`}
                                            closable={false}
                                            color={record.color}
                                        >
                                            {record.color}
                                        </WeaTag>
                                    </span>
                                )
                            }
                        }
                    ]
                }
            ],
            ...props
        }
    }

    componentWillMount() {
        let interval = window.setInterval(() => {         
            const { datas } = this.state
            if (datas.length > 0) {
                this.setState({        // 防止首次加载时draggable不生效
                    datas: [...datas]
                })
                window.clearInterval(interval)
            }
        }, 500)

        this.getTaskTagList()
    }

    componentWillReceiveProps(newProps) {
        this.setState({
            ...this.state,
            ...newProps
        })
    }

    componentDidMount() {

    }

    componentDidUpdate() {

    }

    componentWillUnmount() {

    }

    onSearch = () => {
        const { searchname } = this.state
        this.getTaskTagList({
            searchname: searchname.trim()
        })
    }

    getTaskTagList = (params = {}) => {
        this.setState({
            spinning: true
        })
        taskMain.taskTag({ operate: 'searchList', ...params }).then(res => {
            this.setState({
                datas: res.datas || [],
                spinning: false
            })
        })
    }

    onlyClose = (type) => {
        const { onlyClose } = this.state
        if (typeof onlyClose === "function") {
            onlyClose(type)
        }
    }

    onTagClick = (tag) => {
        this.setState({
            targetTag: tag,
            colorpickerDialogVisible: true
        })
    }

    onAddTag = () => {
        const { datas } = this.state
        this.setState({
            datas: [...datas, {
                id: guid(),
                name: "",
                color: "#" + Math.random().toString(16).slice(2, 8),
                canedit: true
            }]
        })
    }

    onDelTag = (newDatas, delIdsArray) => {
        return new Promise((resolve, reject) => {
            const { delTagIds } = this.state
            this.setState({
                datas: newDatas,
                delTagIds: delTagIds ? delTagIds + "," + delIdsArray.join(",") : delIdsArray.join(",")
            }, () => {
                resolve(true)
            })
        })
    }

    saveTag = () => {
        const { datas, delTagIds } = this.state
        const { onlyClose } = this.state

        let canSave = true
        datas.forEach((d, i) => {
            if (!(d.name && d.name.trim())) {
                canSave = false
            }
        })

        if (canSave) {
            taskMain.taskTag({
                operate: 'saveBatch',
                datas: JSON.stringify(datas),
                delTagIds
            }).then(res => {
                if (res.status == 1) {
                    // message.success(getLabel('22619', '保存成功'))
                    typeof onlyClose === "function" && onlyClose("1", datas)
                } else {
                    // message.error(getLabel('383746', '请求失败'))
                }
            })
        } else {
            Modal.warning({
                title: getLabel(558, '提示'),
                content: getLabel(506468, '标签名称不能为空!')
            })
        }
    }

    onSequenceChange = (datas) => {
        this.setState({
            datas
        })
    }

    onTagColorSave = () => {
        const { datas, targetTag } = this.state
        datas.forEach((d, i) => {
            if (d.id == targetTag.id) {
                d.color = targetTag.color
            }
        })

        this.setState({
            colorpickerDialogVisible: false,
            datas: [...datas]
        })
    }

    render() {
        const { createvisable = false, datas, spinning, disabledIds = [], columns, moreButtons, colorpickerDialogVisible, targetTag, searchname } = this.state

        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@n44e04`}
                visible={createvisable}
                title={getLabel(30884, '标签设置')}
                icon="icon-coms-implement"
                iconBgcolor="rgb(150, 53, 138)"
                buttons={
                    [
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@eah6nm@save`} type="primary" onClick={this.saveTag}>{getLabel(86, '保存')}</Button>,
                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@14w4tj@cancel`} onClick={() => this.onlyClose("0")}>{getLabel(201, '取消')}</Button>
                    ]
                }
                style={{ width: 800, height: window.innerHeight * 0.8 }}
                closable={true}
                onCancel={() => this.onlyClose("0")}
                ref={ref => {
                    if (ref) {
                        this.dialogBodyHeight = ref.state.height || 0
                    }
                }}
            >
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@uv1164`} spinning={spinning}>
                    <div
                        className="wea-workrelate-task-tag"
                        style={{ overflow: "auto" }}
                        ref={ref => {
                            if (ref) {
                                ref.style.height = this.dialogBodyHeight + "px"
                            }
                        }}
                    >
                        <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@rzr0x2`}
                            rowKey={"id"}
                            title={
                                <div className="task-tag-title-div">
                                    <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@5oolmy`}
                                        placeholder={getLabel(81323, '标签名称')}
                                        value={searchname}
                                        onSearchChange={(v) => this.setState({ searchname: v })}
                                        onSearch={() => this.onSearch()}
                                    />
                                </div>
                            }
                            datas={datas}
                            draggable={true}
                            draggableType={"icon"}
                            columns={columns}
                            showCopy={false}
                            willAdd={this.onAddTag}
                            willDelete={this.onDelTag}
                            onChange={this.onSequenceChange}
                            getRowSelection={(rowSelection) => {
                                const sel = { ...rowSelection }
                                sel.getCheckboxProps = record => {
                                    // return { disabled: disabledIds.indexOf(record.id + "") !== -1 }
                                    return { disabled: false }
                                }
                                return sel
                            }}
                        />
                        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@pk2bcr`}
                            visible={colorpickerDialogVisible}
                            title={getLabel(495, '颜色')}
                            icon="icon-coms-implement"
                            iconBgcolor="rgb(150, 53, 138)"
                            style={
                                {
                                    width: 400,
                                    height: 100
                                }
                            }
                            onCancel={() => this.setState({ colorpickerDialogVisible: false })}
                            buttons={
                                [
                                    <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@d78wmc@save`} type="primary" onClick={this.onTagColorSave}>{getLabel(86, '保存')}</Button>
                                ]
                            }
                            children={
                                <div style={{ position: "relative", top: "35%", left: "35%" }}>
                                    <WeaColorPicker ecId={`${this && this.props && this.props.ecId || ''}_WeaColorPicker@rx5tp6`}
                                        value={targetTag.color}
                                        onChange={(value) => {
                                            targetTag.color = value
                                            this.setState({
                                                targetTag
                                            })
                                        }}
                                    />
                                </div>
                            }
                        />
                    </div>
                </Spin>
            </WeaDialog>
        )
    }
}